#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
    const vector<vector<int>> dir = {{-1, -1}, {-1, 1}, {1, 1}, {1, -1}};
    int n, m;

    bool isValid(int r, int c) {
        return r >= 0 && r < n && c >= 0 && c < m;
    }


    int getClockwiseTurn(int dir_idx) {
        return (dir_idx + 1) % 4;
    }

    int getExpectedValue(int len) {
        return (len % 2 == 0) ? 2 : 0;
    }

    int dfs_second_leg(const vector<vector<int>>& g, int r, int c, int len, int dir_idx) {
        int max_len_from_here = len; 

        int next_r = r + dir[dir_idx][0];
        int next_c = c + dir[dir_idx][1];
        
        if (isValid(next_r, next_c) && g[next_r][next_c] == getExpectedValue(len + 1)) {
            max_len_from_here = max(max_len_from_here, dfs_second_leg(g, next_r, next_c, len + 1, dir_idx));
        }
        
        return max_len_from_here;
    }

    int dfs_first_leg(const vector<vector<int>>& g, int r, int c, int len, int dir_idx) {
        int max_len_found = len;

        int turn_dir_idx = getClockwiseTurn(dir_idx);
        int next_r_turn = r + dir[turn_dir_idx][0];
        int next_c_turn = c + dir[turn_dir_idx][1];

        if (isValid(next_r_turn, next_c_turn) && g[next_r_turn][next_c_turn] == getExpectedValue(len + 1)) {

            max_len_found = max(max_len_found, dfs_second_leg(g, next_r_turn, next_c_turn, len + 1, turn_dir_idx));
        }

        int next_r_straight = r + dir[dir_idx][0];
        int next_c_straight = c + dir[dir_idx][1];
        if (isValid(next_r_straight, next_c_straight) && g[next_r_straight][next_c_straight] == getExpectedValue(len + 1)) {
            max_len_found = max(max_len_found, dfs_first_leg(g, next_r_straight, next_c_straight, len + 1, dir_idx));
        }

        return max_len_found;
    }

    int lenOfVDiagonal(const vector<vector<int>>& g) {
        if (g.empty() || g[0].empty()) return 0;
        n = g.size();
        m = g[0].size();
        
        int ans = 0;
        bool has_one = false;

        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                if (g[i][j] == 1) {
                    has_one = true;
                    for (int k = 0; k < 4; ++k) {
                         ans = max(ans, dfs_first_leg(g, i, j, 1, k));
                    }
                }
            }
        }
        if (has_one && ans == 0) return 1;

        return ans;
    }
};


int main(){
    Solution s;
    int ans = s.lenOfVDiagonal({{2,2,1,2,2},{2,0,2,2,0},{2,0,1,1,0},{1,0,2,2,2},{2,0,0,2,2}});
    cout<<ans<<"\n";
}
